package com.offlinerssreader.view;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.offlinerssreader.controller.ActionResponse;
import com.offlinerssreader.controller.ORRController;
import com.offlinerssreader.controller.ReturnableResponse;

/**
 * Servlet implementation class ApiRssItem
 */
public class ApiRssItem extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ServletContext context = null;
	private ORRController controller = null;
	
	@Override
	public void init() {
		this.context = this.getServletContext();
		this.controller = (ORRController) this.context.getAttribute("controller");
		if (this.controller == null) {
			this.controller = ORRController.getInstance();
			this.context.setAttribute("controller", this.controller);
		}
	}
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ApiRssItem() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		Integer userId;
		
		String call = request.getParameter("call");
		ReturnableResponse rtrn = new ActionResponse("nothing", true, "no msg", null);
		HttpSession session = request.getSession(false);
		
		if (session == null) {
			rtrn = new ActionResponse(call, false, "Un auhtorized access to API", null);
		} else {
			if (call == null) {
				rtrn = new ActionResponse("", false, "No call identifier found", null);
			} else {
				userId = (Integer)session.getAttribute("userId");
				if (userId == null) {
					// General error
					rtrn = new ActionResponse(call, false, "General error", null);
				} else {
					if (call.equals("read")) {
						int id = Integer.parseInt(request.getParameter("id"));
						
						rtrn = this.controller.markAsRead(userId, id);
					} else if (call.equals("cache")) {
							int id = Integer.parseInt(request.getParameter("id"));
							
							rtrn = this.controller.markAsCache(userId, id);
					} else {
						rtrn = new ActionResponse(call, false, "Unsupported call in this API", null);
					}
				}
			}
		}
	}

}
